package com.example.springbootdemo.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.springbootdemo.bean.kernelApi.*;
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import lombok.extern.log4j.Log4j2;
import lombok.var;
import org.springframework.stereotype.Service;


@Log4j2
@Service
public class KernelApiServiceImpl implements KernelApiService {


    HubConnection hubConnection;

    HubConnection kernelHubConnection;

    @Override
    public void connect() {

        hubConnection = HubConnectionBuilder.create("https://orginone.cn/orginone/anydata/hub")
                .build();
        hubConnection.setKeepAliveInterval(3000);
        hubConnection.onClosed((err) -> {
            try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            hubConnection.start().blockingAwait();
        });
        hubConnection.start().blockingAwait();
    }

    @Override
    public Result<ThingDataObj> loadThing(String belongId, int page, int pageSize) {
        try {
            var type = new Result<ThingDataObj>();
            var search = new ThingSearchReq();
            search.setSkip((page - 1) * pageSize);
            search.setTake(pageSize);
            search.getSort().add(new Sort("T472763800383262720", true));
            var result = hubConnection.invoke(type.getClass(), "Load", belongId, search).blockingGet();

            var json = JSON.toJSONString(result);
            var obj = JSON.parseObject(json, new TypeReference<Result<ThingDataObj>>(){});

            log.info(obj);
            return obj;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return null;
    }

    private String account;
    private String pwd;

    private String token;


    @Override
    public String login(String userName, String password) {
        account = userName;
        pwd = password;

        LoginReq req = new LoginReq(userName, password);
        var type = new Result<LoginData>();
        var result = hubConnection.invoke(type.getClass(), "login", req).blockingGet();
        var obj = getJsonData(result,LoginData.class);
        token = obj.getData().getAccessToken();
        return token;
    }

    @Override
    public void tokenAuth(String token){
        hubConnection.invoke("TokenAuth", token).blockingAwait();
    }

    private <T> Result<T> getJsonData(Object obj, Class<T> clazz){
        var json = JSON.toJSONString(obj);
        var result = JSON.parseObject(json, new TypeReference<Result<T>>(clazz){});
        return result;
    }
}
